<template>
    <div id="news-list">
        <table class="table table-bordered table-hover">
            <thead>
            <tr>
                <th>标题</th>
                <th>类别</th>
                <th>来源</th>
                <th>发布时间</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="n in newsList" :key="n.id">
                <td>{{ n.title }}</td>
                <td>{{ showMyCateName(n.cate) }}</td>
                <td>{{ n.source }}</td>
                <td>{{ n.pub_time }}</td>
                <td>
                    <router-link :to="'/edit?id=' + n.id" class="btn btn-link">修改</router-link>
                    <button class="btn btn-link" @click="remove(n.id)">删除</button>
                    <button class="btn btn-link">查看</button>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
import cate from "@/service/cate";
import news from "@/service/news";

export default {
    name: "Home",
    components: {},
    data() {
        return {
            newsList: [],
            category:{
                all:[],
                map:{}
            }
        }
    },
    mounted() {
        this.loadCategory()
    },
    methods: {
        showMyCateName(alias){
            if(alias && this.category.map[alias]){
                return this.category.map[alias].title
            }
            return alias
        },
        loadCategory() {
            // 加载分类
            cate.all().then(result=>{
                console.log(result)
                this.category.all = result.data.data
                this.category.all.forEach(c=>{
                    // 将alias作为key进行保存
                    this.category.map[c.alias] = c
                })
                // 先完成分类加载 在加载新闻列表 确保数据的顺序正确
                this.loadNewsList()
            })

        },
        remove(id) {
            news.delete(id).then(resp => {
                if (resp.data.code == 0) {
                    alert('删除成功')
                    this.loadNewsList()
                } else {
                    alert(resp.data.message)
                }
            });
        },
        loadNewsList(page = 1, page_size = 10) {
            news.all(page, page_size).then(resp => {
                this.newsList = resp.data.data
            })
        }
    }
}
</script>

<style scoped>

</style>